import SHA512 from 'crypto-js/sha512';
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import styles from './register.module.css';

const RegisterForm = () => {
  const navigate = useNavigate();
  const [formData, setFormData] = useState({ 
    username: '', 
    password: '',
    confirmPassword: ''
  });
  const [errors, setErrors] = useState({});
  const [submitError, setSubmitError] = useState('');
  const [successMessage, setSuccessMessage] = useState('');

    // 密码校验函数
  const validatePassword = (password) => {
    const errors = [];
    if (password.length < 8) {
      errors.push('密码长度至少为8个字符');
    }
    if (!/\d/.test(password)) {
      errors.push('密码必须包含至少一个数字');
    }
    if (!/[a-zA-Z]/.test(password)) {
      errors.push('密码必须包含至少一个字母');
    }
    return errors;
  };

  // 表单验证
  const validateForm = () => {
    const newErrors = {};
    let isValid = true;

    // 用户名验证
    if (!formData.username.trim()) {
      newErrors.username = '用户名不能为空';
      isValid = false;
    }

    // 密码验证
    const passwordErrors = validatePassword(formData.password);
    if (passwordErrors.length > 0) {
      newErrors.password = passwordErrors.join(', ');
      isValid = false;
    }

    // 确认密码验证
    if (formData.password !== formData.confirmPassword) {
      newErrors.confirmPassword = '两次输入的密码不一致';
      isValid = false;
    }

    setErrors(newErrors);
    return isValid;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setSubmitError('');
    setSuccessMessage('');
    
    // 表单验证
    if (!validateForm()) {
      return;
    }
    
    // 前端SHA-512哈希（非必须但增加安全层）
    const hashedPassword = SHA512(formData.password).toString();
    
    // 发送到后端
    try {
        const res = await axios.post("http://localhost:3000/register", {
          username: formData.username,
          password: hashedPassword
        });
        
        if (res.data.code === 200) {
          // 显示注册成功消息
          setSuccessMessage('注册成功！3秒后跳转到登录页面...');
          
          // 清空表单
          setFormData({ 
            username: '', 
            password: '',
            confirmPassword: ''
          });
          
          // 延迟3秒后跳转到登录页面
          setTimeout(() => {
            navigate("/login");
          }, 3000);
        } else {
          setSubmitError(res.data.message || '注册失败，请稍后重试');
        }
     } catch (error) {
       console.error('注册失败:', error);
       setSubmitError('网络错误，请稍后重试');
     }
  };

  return (
    <div className={styles.registerContainer}>
      <div className={styles.registerBox}>
        <h2 className={styles.registerTitle}>用户注册</h2>
        
        {successMessage && (
          <div className={styles.successMessage}>{successMessage}</div>
        )}
        
        {submitError && (
          <div className={styles.errorMessage}>{submitError}</div>
        )}
        
        <form className={styles.registerForm} onSubmit={handleSubmit}>
          <div className={styles.formGroup}>
            <label className={styles.inputLabel}>用户名</label>
            <input 
              type="text"
              placeholder="请输入用户名"
              value={formData.username}
              onChange={(e) => setFormData({...formData, username: e.target.value})}
            />
            {errors.username && (
              <div className={styles.fieldError}>{errors.username}</div>
            )}
          </div>
          
          <div className={styles.formGroup}>
            <label className={styles.inputLabel}>密码</label>
            <input 
              type="password"
              placeholder="请输入密码(至少8个字符，包含数字和字母)"
              value={formData.password}
              onChange={(e) => setFormData({...formData, password: e.target.value})}
            />
            {errors.password && (
              <div className={styles.fieldError}>{errors.password}</div>
            )}
          </div>
          
          <div className={styles.formGroup}>
            <label className={styles.inputLabel}>确认密码</label>
            <input 
              type="password"
              placeholder="请再次输入密码"
              value={formData.confirmPassword}
              onChange={(e) => setFormData({...formData, confirmPassword: e.target.value})}
            />
            {errors.confirmPassword && (
              <div className={styles.fieldError}>{errors.confirmPassword}</div>
            )}
          </div>
          
          <button type="submit" className={styles.registerButton}>注册</button>
        </form>
        
        <div className={styles.loginLink}>
          已有账号? <a href="/login" onClick={(e) => { e.preventDefault(); navigate('/login'); }}>立即登录</a>
        </div>
      </div>
    </div>
  );
};

export default RegisterForm